import { createContext, useState, useEffect, Dispatch, SetStateAction, useRef } from 'react'
import type { TableProps, TabsProps, SelectProps } from 'antd';
import { Button, Modal, message, Tooltip, Typography } from 'antd';
const { Paragraph } = Typography;
import { DataType, ProperNounsType, SynonymsForType, CaseLibraryType, paginationType } from './type'
import { useRequest } from 'ahooks'
import { STORAGE_USERINFO_KEY } from '@/utils/constants/index';
import { domainList, domainThesaurusDelete, termList, termDelete, applicationList } from '@/client/api/domainThesaurus'
const data: DataType[] = [];
const tablist: TabsProps['items'] = [
    {
        key: 'ProperNouns',
        label: '专有名词',
        children: '',
    },
    {
        key: 'Synonym',
        label: '同义词',
        children: '',
    },
    {
        key: 'CaseLibrary',
        label: '案例库',
        children: '',
    },
];
interface IDthesaurusContext {
    pageType: string,
    tabType: 'ProperNouns' | 'Synonym' | 'CaseLibrary',
    columns: TableProps<DataType>['columns'],
    data: DataType[],
    handleItemClick: (type: string) => void,
    handleDetail: (key: string) => void,
    tablist: TabsProps['items'],
    onChange: (key: string) => void,
    properNounsData: ProperNounsType[],
    properNounsColumns: TableProps<ProperNounsType>['columns'],
    SynonymsForData: SynonymsForType[],
    SynonymsForColumns: TableProps<SynonymsForType>['columns'],
    CaseLibraryData: CaseLibraryType[],
    CaseLibraryColumn: TableProps<CaseLibraryType>['columns'],
    domainRow: any,
    setPageType: (pageType: string) => void,
    createdomainModeloPen: boolean,
    setCreatedomainModeloPen: (createdomainModeloPen: boolean) => void,
    domainOperation: 'add' | 'edit',
    setDomainOperation: (domainOperation: string) => void,
    initdomainData: (page?:number,pageSize?:number) => void,
    createtermModeloPen: boolean,
    setCreatetermModeloPen: (CreatetermModeloPen: boolean) => void
    termRow: Object,
    setTermRow: (TermRow: Object) => void,
    tremEditStatus: 'add' | 'edit',
    setTremEditStatus: (tremEditeStatus: string) => void,
    sub: string,
    login_name: string,
    pagination: paginationType,
    setPagination: Dispatch<SetStateAction<paginationType>>;
    termpagination: paginationType,
    setTermPagination: Dispatch<SetStateAction<paginationType>>,
    filterValue: string,
    filterTermValue: string,
    setFilterTermValue: (filterValue: string) => void,
    setFilterValue: (filterValue: string) => void,
    setDomainRow: (domainRow: any) => void,
    inittermData: (type?:string,page?:number,pageSize?:number) => void,
    options: SelectProps['options'],
    setOption: (options: SelectProps['options']) => void,
    tableHeight: number,
    setTableHeight: (tableHeight: number|void) => void,
    getTableHeight: () => void,
}

const DthesaurusContent = createContext<IDthesaurusContext>({
    pageType: 'list',
    tabType: 'ProperNouns',
    columns: [],
    data: [],
    handleItemClick: (type: string) => { },
    handleDetail: (key: string) => { },
    tablist: [],
    onChange: (key: string) => { },
    properNounsData: [],
    properNounsColumns: [],
    SynonymsForData: [],
    SynonymsForColumns: [],
    CaseLibraryData: [],
    CaseLibraryColumn: [],
    domainRow: {},
    setPageType: (pageType: string) => { },
    createdomainModeloPen: false,
    setCreatedomainModeloPen: (createdomainModeloPen: boolean) => { },
    domainOperation: 'add',
    setDomainOperation: (domainOperation: string) => { },
    initdomainData: (page?:number,pageSize?:number) => { },
    createtermModeloPen: false,
    setCreatetermModeloPen: (CreatetermModeloPen: boolean) => { },
    termRow: {},
    setTermRow: (termRow: Object) => { },
    tremEditStatus: 'add',
    setTremEditStatus: (tremEditStatus: string) => { },
    sub: '',
    login_name:'',
    pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
    },
    setPagination: () => { },
    filterValue: '',
    setFilterValue: (filterValue: string) => { },
    setDomainRow: (domainRow: any) => { },
    inittermData: () => { },
    termpagination: {
        current: 1,
        pageSize: 10,
        total: 0,
    },
    setTermPagination: () => {
    },
    options: [],
    setOption: (options: SelectProps['options']) => { },
    filterTermValue: '',
    setFilterTermValue: (filterValue: string) => { },
    tableHeight: 0,
    setTableHeight: (tableHeight: number|void) => { },
    getTableHeight: () => { },
});

const DthesaurusContentProvider = ({ children }: { children: React.ReactElement }) => {
    const onChange = (key: string) => {
        setTabType(key)
        fetchTermData(key)
    }
    const [data, setData] = useState<DataType[]>([]);
    const [pageType, setPageType] = useState('list');
    const [tabType, setTabType] = useState('ProperNouns');
    const [domainRow, setDomainRow] = useState<any>();
    const [termRow, setTermRow] = useState<any>()
    const [filterValue, setFilterValue] = useState('')
    const [filterTermValue, setFilterTermValue] = useState('')
    const [pagination, setPagination] = useState<paginationType>({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [termpagination, setTermPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    })
    const [createdomainModeloPen, setCreatedomainModeloPen] = useState(false);
    const { sub,login_name } = JSON.parse(localStorage.getItem(STORAGE_USERINFO_KEY) || '{}');
    /*详情  */
    //专业名称弹框
    const [createtermModeloPen, setCreatetermModeloPen] = useState(false);
    //专业名词列表
    const [properNounsData, setProperNounsData] = useState<ProperNounsType[]>([]);
    //同义词
    const [SynonymsForData, setSynonymsForData] = useState<ProperNounsType[]>([]);
    //案例库
    const [CaseLibraryData, setCaseLibraryData] = useState<ProperNounsType[]>([]);
    const [options, setOptions] = useState<SelectProps['options']>([]);
    const [appMap, setAppMap] = useState<Record<string, string>>({});
    //新增编辑状态
    const [tremEditStatus, setTremEditStatus] = useState('add')
    /* 领域列表 */
    //领域词库操作状态
    const [domainOperation, setDomainOperation] = useState('add')

    const [tableHeight, setTableHeight] = useState('auto');


    const getTableHeight = () => {
        const tHeader = document.querySelector('.ant-table-thead');
        const headerBottom = tHeader?.getBoundingClientRect().bottom || 0;
        const paginationHeight = 64; // 分页器高度
        const extraMargin = 20; // 其他边距
        return `calc(100vh - ${headerBottom + paginationHeight + extraMargin}px)`;
    };
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '领域词库名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis:{
                showTitle:false
            },
            render: (text, record) =>(
                <Tooltip placement='topLeft' title={text}>
                     <a onClick={() => {
                handleDetail(record);
                setDomainRow(record)
            }}>{text}</a>
                </Tooltip>
            ),
        },
        {
            title: '描述',
            dataIndex: 'desc',
            key: 'desc',
             ellipsis: {
            showTitle: false,
            },
            render: (desc) => (
            <Tooltip placement="topLeft" title={desc}>
                {desc}
            </Tooltip>
            ),
        },
        {
            title: '创建人',
            dataIndex: 'creator',
            key: 'creator',
        },
        {
            title: '创建时间',
            dataIndex: 'create_datetime',
            key: 'create_datetime',
        },
        {
            title: '修改时间',
            dataIndex: 'update_datetime',
            key: 'update_datetime',
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (_, record) => (
                <div style={{ marginLeft: '-15px' }}>
                    <Button
                        type='link'
                        onClick={() => {
                            handleDetail(record);
                            setDomainRow(record)
                        }}
                    >
                        查看
                    </Button>
                    <Button
                        type='link'
                        onClick={() => {
                            setCreatedomainModeloPen(true)
                            setDomainOperation('edit')
                            setDomainRow(record)
                        }}
                    >
                        编辑
                    </Button>
                    <Button type='link' onClick={() => {
                        deleteDomain(record)
                    }}>删除</Button>
                </div>
            ),
        },
    ];
    const properNounsColumns: TableProps<ProperNounsType>['columns'] = [
        {
            title: '专有名词',
            dataIndex: 'name',
            key: 'name',
            ellipsis:{
                showTitle:false
            },
            render:(name) =>(
                <Tooltip placement='topLeft' title={name}>{name}</Tooltip>
            )
        },
        {
            title: '名词描述',
            dataIndex: 'desc',
            key: 'desc',
            ellipsis: {
            showTitle: false,
            },
            render: (desc) => (
            <Tooltip placement="topLeft" title={desc}>
                {desc}
            </Tooltip>
            ),
        },
        {
            title: '更新时间',
            dataIndex: 'update_datetime',
            key: 'update_datetime',
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (_, record) => {
                return (
                    <div style={{ marginLeft: '-15px' }}>
                        <Button type='link' onClick={() => {
                            setTermRow(record)
                            setTremEditStatus('edit')
                            setCreatetermModeloPen(true)
                        }}>编辑</Button>
                        <Button type='link' onClick={() => {
                            deleteTerm(record)
                        }}>删除</Button>
                    </div>
                )
            }
        }
    ]
    const SynonymsForColumns: TableProps<SynonymsForType>['columns'] = [
        {
            title: '标准名词',
            dataIndex: 'name',
            key: 'name',
            ellipsis:{
                showTitle:false
            },
            render:(name)=>(
                <Tooltip placement='topLeft' title={name}>{name}</Tooltip>
            )
        },
        {
            title: '同义词',
            dataIndex: 'desc',
            key: 'desc',
            ellipsis:{
                showTitle:false
            },
            render:(desc)=>(
                <Tooltip placement='topLeft' title={desc}>{desc}</Tooltip>
            )
        },
        {
            title: '更新时间',
            dataIndex: 'update_datetime',
            key: 'update_datetime',
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',

            render: (_, record) => {
                return <div style={{ marginLeft: '-15px' }}>
                    <Button type='link' onClick={() => {
                        setTremEditStatus('edit')
                        setCreatetermModeloPen(true)
                        let data = {
                            ...record,
                            desc: record.desc ? record.desc.split(',') : []
                        }
                        setTermRow(data)
                    }}>编辑</Button>
                    <Button type='link' onClick={() => {

                        deleteTerm(record)
                    }}>删除</Button>
                </div>
            }
        }
    ]
    const CaseLibraryColumn: TableProps<CaseLibraryType>['columns'] = [
        {
            title: '所属应用',
            dataIndex: 'app_code',
            key: 'app_code'
        },
        {
            title: '用户输入',
            dataIndex: 'name',
            key: 'name',
             ellipsis: {
            showTitle: false,
            },
            render: (name) => (
            <Tooltip placement="topLeft" title={name}>
                {name}
            </Tooltip>
            ),
        },
        {
            title: "期望输出",
            dataIndex: 'desc',
            key: 'desc',
            render: (text: string) => (
                <Tooltip placement="topLeft" title={text}>
                    <Paragraph
                        ellipsis={{ rows: 2, expandable: false }}
                        style={{ margin: 0, maxWidth: 300 }}
                    >
                        <span className='cursor-pointer'>{text}</span>
                    </Paragraph>
                </Tooltip>
            ),
        },
        {
            title: "操作",
            dataIndex: 'action',
            key: 'action',
            render: (_, record) => {
                return <div style={{ marginLeft: '-15px' }}>
                    <Button type='link' onClick={() => {
                        setTremEditStatus('edit')
                        setCreatetermModeloPen(true)
                        setTermRow(record)
                    }}>编辑</Button>
                    <Button type='link' onClick={() => {
                        deleteTerm(record)
                    }}>删除</Button>
                </div>
            }
        }
    ]
    const handleItemClick = (type: string) => {
        setPageType(type);
    };

    const handleDetail = (data: Object) => {
        setDomainRow(data)
        setPageType('detail');
    };
    //删除领域
    const { run: delDomain } = useRequest(async (row: any) => {
        return await domainThesaurusDelete({
            id: row.id
        })

    },
        {
            manual: true,
            onSuccess: (res: any) => {
                const { success, err_msg } = res.data || {}
                if (success) {
                    fetchDomainData()
                    message.success('删除成功')
                } else {
                    message.error(err_msg)
                }
            }
        }
    )
    //领域列表操作方法
    const deleteDomain = async (row: object) => {
        Modal.confirm({
            title: '删除词库',
            content: <>{`确定要删除该${row.name}吗？`}<br /><span className='text-gray-300 text-xs'>删除后将无法恢复</span></>,
            okText: '确认',
            cancelText: '取消',
            okType: 'danger',
            onOk: async () => {
                try {
                    delDomain(row)
                } catch (error) {
                    console.error('删除失败', error);
                }
            },
            onCancel: () => {
                console.log('取消删除');
            },
        });
    }
    //获取领域列表
    const { run: fetchDomainData } = useRequest(
        async (page?: number, pageSize?: number) => {
            let data = {
                page: page ? page : pagination.current,
                page_size: pageSize ? pageSize : pagination.pageSize,
                keyword: filterValue
            }
            return await domainList(data)
        }, {
        manual: true,
        onSuccess: (res: any) => {
            const { data, success } = res.data || {}
            if (success) {
                setData(data.items)
                setPagination({
                    ...pagination,
                    total: data.total_count,
                })
            } else {
                message.error(data)
            }
        }
    }
    )
    //术语列表
    const { run: fetchTermData } = useRequest(async (type?: string, page?: number, pageSize?: number) => {
        return await termList({
            page: page ? page : termpagination.current,
            page_size: pageSize ? pageSize : termpagination.pageSize,
            type: type ? type : tabType,
            lexicon_domain_id: domainRow.id,
            keyword: filterTermValue
        })
    }, {
        manual: true,
        onSuccess: (res: any) => {
            const { data, success } = res.data || {}
            if (success) {
                if (tabType === 'ProperNouns') {
                    setProperNounsData(data.items)
                } else if (tabType === 'Synonym') {
                    setSynonymsForData(data.items)
                } else {
                    data.items.map((item: any) => {
                        item.app_code = appMap[item.app_code]
                    })
                    setCaseLibraryData(data.items)
                }

                setTermPagination({
                    ...termpagination,
                    total: data.total_count
                })
            }
        }
    })
    //删除术语deleteTerm
    const deleteTerm = async (row: object) => {
        Modal.confirm({
            title: '删除',
            content: <>{tabType !== 'CaseLibrary' ? `正在删除${row.name},删除后无法恢复,确认是否删除？` : `删除后无法恢复,确认是否删除？`}</>,
            okText: '确认',
            cancelText: '取消',
            okType: 'danger',
            onOk: async () => {
                try {
                    delTerm(row)
                } catch (error) {
                    console.error('删除失败', error);
                }
            },
            onCancel: () => {
                console.log('取消删除');
            },
        });
    }
    //删除领域
    const { run: delTerm } = useRequest(async (row: any) => {
        return await termDelete({
            id: row.id
        })

    },
        {
            manual: true,
            onSuccess: (res: any) => {
                const { success, err_msg } = res.data || {}
                if (success) {
                    fetchTermData()
                    message.success('删除成功')
                } else {
                    message.error(err_msg)
                }
            }
        }
    )
    //应用管理数据
    const { run: applist } = useRequest(async () => {
        return await applicationList({})
    }, {
        manual: true,
        onSuccess: (res: any) => {
            const { data, success } = res.data || {}
            if (success) {
                data.app_list?.unshift({ app_code: '-1', app_name: '全部' })
                const newOption = data.app_list?.map((item: any) => ({ value: item.app_code, label: item.app_name })) || []
                setOptions(newOption)
                // 转换为 key-value 对象格式
                const newAppMap = data.app_list?.reduce((map, item) => {
                    map[item.app_code] = item.app_name;
                    return map;
                }, {}) || {};
                setAppMap(newAppMap);
            }
        }
    })
    useEffect(() => {
        applist()
    }, [])
    const contextValues = {
        pageType,
        columns,
        data,
        handleItemClick,
        handleDetail,
        tablist,
        onChange,
        properNounsColumns,
        properNounsData,
        SynonymsForData,
        SynonymsForColumns,
        tabType,
        CaseLibraryColumn,
        CaseLibraryData,
        domainRow,
        setPageType,
        createdomainModeloPen,
        setCreatedomainModeloPen,
        domainOperation,
        setDomainOperation,
        initdomainData:fetchDomainData,
        inittermData:fetchTermData,
        createtermModeloPen,
        setCreatetermModeloPen,
        termRow,
        setTermRow,
        tremEditStatus,
        setTremEditStatus,
        sub,
        login_name,
        pagination,
        setPagination,
        filterValue,
        setFilterValue,
        termpagination,
        setTermPagination,
        options,
        setOptions,
        setDomainRow,
        filterTermValue,
        setFilterTermValue,
        tableHeight,
        setTableHeight,
        getTableHeight
    };

    return <DthesaurusContent.Provider value={contextValues}>{children}</DthesaurusContent.Provider>;
};

export { DthesaurusContent, DthesaurusContentProvider };